package com.fy.opengltest.renderSphere;

import android.content.Intent;
import android.net.Uri;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.util.SparseArray;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import com.fy.opengltest.Car360.MDFlingConfig;
import com.fy.opengltest.Car360.MDPinchConfig;
import com.fy.opengltest.Car360.MDTouchHelper;
import com.fy.opengltest.R;
import com.fy.opengltest.SpinnerHelper;

public class ActivitySphere extends AppCompatActivity implements View.OnClickListener {


    private GLSurfaceView glSurfaceView;
    private GLSphereObjectRenderer mRenderer = null;

    private TextView paramsTextView;

    MDTouchHelper mdTouchHelper;
    SpinnerHelper mSpinnerHelper;
    int mSelectType = 1;
    int mSelectParam;


    private MDPinchConfig pinchConfig = new MDPinchConfig();

    protected Uri getUri() {
        Intent i = getIntent();
        if (i == null || i.getData() == null) {
            return null;
        }
        return i.getData();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sphere);
        paramsTextView = (TextView) findViewById(R.id.params);
        glSurfaceView = (GLSurfaceView) findViewById(R.id.gl_surface_view);
        glSurfaceView.setEGLContextClientVersion(2);
        mRenderer = new GLSphereObjectRenderer(this, getUri());
        glSurfaceView.setRenderer(mRenderer);
        mdTouchHelper = new MDTouchHelper(this);
        mdTouchHelper.setGestureListener(gestureListener);
        mdTouchHelper.setFlingConfig(new MDFlingConfig());
        mdTouchHelper.setPinchConfig(pinchConfig);
        glSurfaceView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return mdTouchHelper.handleTouchEvent(event);
            }
        });

        SpinnerHelper spinnerHelper;
        SparseArray<String> data = new SparseArray<>();
        data.put(0, "Camera");
        data.put(1, "Model");
        data.put(2, "Calibrate");
        spinnerHelper = SpinnerHelper.with(this)
                .setDefault(mSelectType)
                .setData(data)
                .setClickHandler(new SpinnerHelper.ClickHandler() {
                    @Override
                    public void onSpinnerClicked(int index, int key, String value) {
                        if (mSelectType == key) {
                            return;
                        }
                        onTypeChange(key);
                        updateRange(mSelectType, mSelectParam);
                    }
                });
        spinnerHelper.init(R.id.control_type);

        mSpinnerHelper = SpinnerHelper.with(this)
                .setData(getDataByType(mSelectType))
                .setDefault(mSelectParam)
                .setClickHandler(new SpinnerHelper.ClickHandler() {
                    @Override
                    public void onSpinnerClicked(int index, int key, String value) {
                        if (mSelectParam == key) {
                            return;
                        }
                        mSelectParam = key;
                        updateRange(mSelectType, mSelectParam);
                    }
                });
        mSpinnerHelper.init(R.id.control_param);
        updateText();
        updateRange(mSelectType, mSelectParam);

        findViewById(R.id.inc_btn).setOnClickListener(this);
        findViewById(R.id.dec_btn).setOnClickListener(this);
        dimStatusBar(true);
    }

    private SparseArray<String> getDataByType(int type) {
        switch (type) {
            case 0:
                return camera;
            case 1:
                return model;
            case 2:
                return calibrate;
        }
        return null;
    }

    void updateValue(int type, int param, boolean add) {
        float value = mRenderer.getValue(type, param);
        float max = 0f;
        float min = 0f;
        switch (type) {
            case 0:
                min = rangeCamera[param][0];
                max = rangeCamera[param][1];
                break;
            case 1:
                min = rangeModel[param][0];
                max = rangeModel[param][1];
                break;
            case 2:
                min = rangeCalibrate[param][0];
                max = rangeCalibrate[param][1];
                break;
        }
        if (add) {
            value += (max - min) / 100f;
        } else {
            value -= (max - min) / 100f;
        }
        if (value < min) {
            value = min;
        } else if (value > max) {
            value = max;
        }
        pinchConfig.setDefaultValue(value);
        pinchConfig.setMax(max);
        pinchConfig.setMin(min);
        pinchConfig.setSensitivity((max - min) / 20f);
        mdTouchHelper.setPinchConfig(pinchConfig);
        Log.d(TAG, " value=" + value + " max=" + max + " min=" + min + " sens=" + ((max - min) / 2f));
    }

    void updateRange(int type, int param) {
        float value = mRenderer.getValue(type, param);
        float max = 0f;
        float min = 0f;
        switch (type) {
            case 0:
                min = rangeCamera[param][0];
                max = rangeCamera[param][1];
                break;
            case 1:
                min = rangeModel[param][0];
                max = rangeModel[param][1];
                break;
            case 2:
                min = rangeCalibrate[param][0];
                max = rangeCalibrate[param][1];
                break;
        }
        pinchConfig.setDefaultValue(value);
        pinchConfig.setMax(max);
        pinchConfig.setMin(min);
        pinchConfig.setSensitivity((max - min) / 20f);
        mdTouchHelper.setPinchConfig(pinchConfig);
        Log.d(TAG, " value=" + value + " max=" + max + " min=" + min + " sens=" + ((max - min) / 2f));
    }

    void updateText() {
        paramsTextView.setText(mRenderer.getParams());
    }

    void onTypeChange(int key) {
        mSelectType = key;
        switch (key) {
            case 0:
                mSpinnerHelper.updateData(camera, R.id.control_param);
                break;
            case 1:
                mSpinnerHelper.updateData(model, R.id.control_param);
                break;
            case 2:
                mSpinnerHelper.updateData(calibrate, R.id.control_param);
                break;
        }
    }

    static SparseArray<String> camera = new SparseArray<>();
    static SparseArray<String> model = new SparseArray<>();
    static SparseArray<String> calibrate = new SparseArray<>();

    static float[][] rangeCamera = {
            {-1000f, 1000f},
            {-1000f, 1000f},
            {-1000f, 1000f},

            {-1f, 1f},
            {-1f, 1f},
            {-1f, 1f},

            {-1f, 1f},
            {-1f, 1f},
            {-1f, 1f},
    };

    static float[][] rangeModel = {
            {-20f, 20f},
            {-20f, 20f},
            {-20f, 60f},

            {0f, 360f},
            {0f, 360f},
            {0f, 360f},

            {0f, 360f},
            {0f, 360f},
            {0f, 360f},
    };

    static float[][] rangeCalibrate = {
            {-1f, 1f},
            {-1f, 1f},
            {-2f, 2f},
            {18f, 500f},
            {0f, 360f},
    };


    static {
        camera.put(0, "eyeX");
        camera.put(1, "eyeY");
        camera.put(2, "eyeZ");
        camera.put(3, "lookX");
        camera.put(4, "lookY");
        camera.put(5, "lookZ");
        camera.put(6, "upX");
        camera.put(7, "upY");
        camera.put(8, "upZ");

        model.put(0, "mX");
        model.put(1, "mY");
        model.put(2, "mZ");
        model.put(3, "mAngleX");
        model.put(4, "mAngleY");
        model.put(5, "mAngleZ");
        model.put(6, "mPitch(x-axis)");
        model.put(7, "mYaw(y-axis)");
        model.put(8, "mRoll(z-axis)");

        calibrate.put(0, "OffsetX");
        calibrate.put(1, "OffsetY");
        calibrate.put(2, "RadiusCal");
        calibrate.put(3, "Radius");
        calibrate.put(4, "degree");
    }

    private static final String TAG = "Car360";
    MDTouchHelper.GestureListener gestureListener = new MDTouchHelper.GestureListener() {

        @Override
        public boolean onDrag(float dis_x, float dis_y) {
//            Log.d(TAG, "onDrag dis_x=" + dis_x + " dis_y=" + dis_y);
            return false;
        }

        @Override
        public boolean onClick(MotionEvent e) {
            View view = findViewById(R.id.control_layout);
            if (view.getVisibility() == View.VISIBLE) {
                view.setVisibility(View.GONE);
            } else {
                view.setVisibility(View.VISIBLE);
            }
            return false;
        }

        @Override
        public boolean onPinch(float dis) {
            Log.d(TAG, "onPinch dis=" + dis);
            mRenderer.handValueChange(mSelectType, mSelectParam, dis);
            updateText();
            return false;
        }
    };

    @Override
    public void onClick(View v) {
        dimStatusBar(true);
        switch (v.getId()) {
            case R.id.inc_btn:
                updateValue(mSelectType, mSelectParam, true);
                break;
            case R.id.dec_btn:
                updateValue(mSelectType, mSelectParam, false);
                break;
        }
    }


    public void dimStatusBar(boolean dim) {
        int visibility;
        int navbar;

        visibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
        navbar = View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
        if (dim) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
            navbar |= View.SYSTEM_UI_FLAG_LOW_PROFILE;
            navbar |= View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
            visibility |= View.SYSTEM_UI_FLAG_IMMERSIVE;
            visibility |= View.SYSTEM_UI_FLAG_FULLSCREEN;
        } else {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
            visibility |= View.SYSTEM_UI_FLAG_VISIBLE;
        }

        visibility |= navbar;
        getWindow().getDecorView().setSystemUiVisibility(visibility);
    }
}
